package com.mercury.design.adaptee;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;

/**
 * @author mercury
 * @date 2022/8/9 09:27
 */
@Component
public class ApiHandlerFactory implements InitializingBean, ApplicationContextAware {


    private ApplicationContext applicationContext;

    private static final String HANDLER_ADAPTER_BEAN_NAME = "apiHandlerAdapter";

    private static List<ApiHandlerAdapter> handlerAdapters;


    public static ApiHandlerAdapter getApiHandlerAdapter(Object handler) {
        if (handlerAdapters != null){
            for (ApiHandlerAdapter handlerAdapter : handlerAdapters) {
                if (handlerAdapter.supports(handler)) {
                    return handlerAdapter;
                }
            }
        }
        throw new RuntimeException("没找到默认的适配器");
    }

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() {
        ApiHandlerAdapter ha = applicationContext.getBean(HANDLER_ADAPTER_BEAN_NAME, ApiHandlerAdapter.class);
        handlerAdapters = Collections.singletonList(ha);
    }
}
